package com.ice.framework.web.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Properties;

/**
 * @author wangwei
 * @Date 2021/12/20 14:48
 */
@Component
public class ConfigHelper implements EnvironmentAware {

    private static Logger logger = LoggerFactory.getLogger(ConfigHelper.class);

    private static final String ENCODING = "UTF-8";

    private static final String ServiceConfigClassPath = "classpath:config/*.properties";

    private static final String RootProperties = "classpath:*.properties";

    private static Environment environment;

    private static final Properties properties = new Properties();


    static {
        try {
            initServiceConfig();
        } catch (IOException e) {
            logger.error("初始化加载配置文件失败=============>classpath:config");
        }

        try {
            iniRootProperties();
        }catch (Exception e) {
            logger.error("初始化加载配置文件失败=============>*.properties");
        }
    }

    /**
     * 初始化服务配置文件
     *
     * @return
     * @throws IOException
     */
    private static void initServiceConfig() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("config");

        boolean exists = classPathResource.exists();
        if (!exists) {
            return;
        }

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // Config
        Resource[] resourceList = resolver.getResources(ServiceConfigClassPath);
        for (Resource resource : resourceList) {
            read(resource);
        }
    }

    /**
     * 初始化服务配置文件
     *
     * @return
     * @throws IOException
     */
    public static void iniRootProperties() throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // Config
        Resource[] resourceList = resolver.getResources(RootProperties);
        for (Resource resource : resourceList) {
            read(resource);
        }
    }

    /**
     * 读取配置文件
     *
     * @author liaohongjian
     * @since 2017年8月22日
     * @param resource
     * @throws IOException
     */
    private static void read(Resource resource) throws IOException {
        if (resource == null) {
            return;
        }

        ResourcePropertySource config = new ResourcePropertySource(new EncodedResource(resource, ENCODING));

        String[] names = config.getPropertyNames();
        for (String key : names) {
            properties.put(key, config.getProperty(key));
        }
    }

    /**
     * 获取属性配置
     *
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        String value = null;

        if(environment != null) {
            value = environment.getProperty(key);
        }

        if (value == null) {
            value = properties.getProperty(key);
        }

        return value == null ? null : value.toString().trim();
    }

    /**
     * 获取当前的环境
     *
     * @return
     *
     * @author wangwei
     * @date 2021年1月18日 下午2:33:52
     */
    public static String getEnvironmentActive() {
        return getProperty("spring.profiles.active");
    }

    /**
     * 是否是本地环境（包括 本地环境和开发环境，不包括TEST/UAT/PROD)
     *
     * @return
     *
     * @author wangwei
     * @date 2021年2月2日 下午9:05:10
     */
    public static boolean isLocalEnv() {
        String env = getEnvironmentActive();
        return "dev".equals(env) || "local".equals(env);
    }

    /**
     * 判断是否开发环境
     * @return
     *
     * @author wangwei
     * @date 2021年2月2日 下午9:05:10
     */
    public static boolean isDevEnv() {
        String env = getEnvironmentActive();
        return "dev".equals(env);
    }

    /**
     * 判断是否测试环境
     * @return
     *
     * @author wangwei
     * @date 2021年2月2日 下午9:05:10
     */
    public static boolean isTestEnv() {
        String env = getEnvironmentActive();
        return "test".equals(env);
    }

    /**
     * 是否是生产环境
     *
     * @return
     * @author wangwei
     * @date 2021年2月2日 下午9:05:10
     */
    public static boolean isProdEnv() {
        String env = getEnvironmentActive();
        return "prod".equals(env);
    }

    /**
     * 获取应用代码
     *
     * @return
     *
     * @author wangwei
     * @date 2021年4月27日 下午4:30:44
     */
    public static String getApplicationName() {
        return getProperty("spring.application.name");
    }

    @Override
    public void setEnvironment(Environment env) {
        environment = env;
    }
}
